package com.csproj.basic.repository.impl;

import com.csproj.basic.domain.Container;
import com.csproj.basic.repository.custom.ContainerRepositoryCustom;
import net.logstash.logback.encoder.org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.HashMap;
import java.util.Map;

public class ContainerRepositoryImpl implements ContainerRepositoryCustom {
    @PersistenceContext
    private EntityManager em;

    public EntityManager getEm() {
        return em;
    }

    /**
     * 机构分页查询方法
     * @param map	参数
     * @param pageable		分页对象
     * @return
     */
    public Page<Container> findPageList(Map<String, Object> map, Pageable pageable) {
        //拼hql
        String hql = " from Container wh where wh.deletedFlag = 0 and (wh.dptFlag!= true or wh.dptFlag = null) ";
        Map<String,Object> queryParams = new HashMap<>();

        String creatorId = (String)map.get("creatorUserId");
        if(StringUtils.isNotBlank(creatorId)){
            hql += " or wh.creator_user_id = :creatorId";
            queryParams.put("creatorId",creatorId);
        }
        String name = (String) map.get("containerNo");

        if (StringUtils.isNotBlank(name)) {
            hql += " and wh.containerNo like :containerNo";
            queryParams.put("containerNo","%"+name+"%");
        }
        String companyId = (String) map.get("containerCompanyId");
        if (StringUtils.isNotBlank(companyId)) {
            hql += " and wh.containerCompanyId like :containerCompanyId";
            queryParams.put("containerCompanyId",companyId);
        }else{
            String siteId = (String) map.get("siteId");
            if(StringUtils.isNotBlank(siteId) && !siteId.equals("nositeID")){
                hql += " and exists (select ui.siteId from UserInfo ui where ui.id=wh.creatorUserId and ui.siteId=:usiteId)";
                queryParams.put("usiteId",siteId);
            }
        }


        //查询
        Page<Container> fieldList = query(hql, pageable, queryParams);
        //返回
        return fieldList;
    }
}
